import React, {useState} from 'react';
import {Animated, Easing} from 'react-native';

export type SpinnerIndicatorProps = {
    size?: number;
    color?: string;
};
const SpinnerIndicator = (props: SpinnerIndicatorProps) => {
    const {size = 24, color = '#5e6977'} = props;
    const animation = React.useRef<Animated.CompositeAnimation>();
    const [animate, setAnimate] = useState(new Animated.Value(0));

    React.useLayoutEffect(() => {
        if (!animation.current) {
            animation.current = Animated.loop(
                Animated.timing(animate, {
                    toValue: 360,
                    duration: 1200,
                    useNativeDriver: true,
                    easing: Easing.linear,
                }),
                {
                    resetBeforeIteration: true,
                    iterations: -1,
                },
            );
        } else {
            animation.current?.reset();
        }

        animation.current?.start();

        return () => {
            animation.current?.stop();
        };
    }, []);

    return (
        <Animated.Image
            source={require('./assets/loading.png')}
            style={{
                width: size,
                height: size,
                tintColor: color,
                transform: [
                    {
                        rotate: animate.interpolate({
                            inputRange: [0, 360],
                            outputRange: ['0deg', '360deg'],
                        }),
                    },
                ],
            }}
        />
    );
};

export default React.memo(SpinnerIndicator);
